import { _decorator, Component, Enum, Label } from 'cc';
import { GameManager } from '../Manager/GameManager';
import { DateUtil } from '../../Util/DateUtil';
import { autoComp, rootNode } from '../Manager/BaseManager';
const { ccclass, property, menu } = _decorator;

export enum ActiveTimeType {
  /** 倒计时 */
  COUNT_DOWN = 0,
  /** 到某个时间点循环 */
  LOOP_POINT = 1,
  /** 多长时间循环 */
  LOOP_TIME = 2,
}

@ccclass('ActiveTime')
@menu('myComponent/ActiveTime')
export class ActiveTime extends Component {
  @property({ type: Enum(ActiveTimeType) })
  type: ActiveTimeType = ActiveTimeType.COUNT_DOWN;
  @property({
    tooltip: '循环时间点(毫秒)->从周日0点到时间点的毫秒数\n循环时间(毫秒)->多长时间后循环',
    visible() {
      return this.type === ActiveTimeType.LOOP_POINT || this.type === ActiveTimeType.LOOP_TIME;
    },
  })
  loopTimePoint: number = 0;
  @property
  timeMode: string = '重置剩余时间   {dd}天{hh}:{mm}:{ss}';
  // @autoComp(Label, rootNode)
  timeLab: Label;
  /** 参考时间点(秒) */
  refTimePoint: number = 0;
  activeTime: number = 0;
  // protected onLoad(): void {
  //   this.timeLab = this.node.getComponent(Label);
  // }
  protected onEnable(): void {
    this.timeLab = this.node.getComponent(Label);
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  update(dt: number): void {
    if (this.activeTime > 0) {
      this.updateTime(GameManager.TimeControl.nowTime);
    }
  }

  /**更新时间 */
  updateTime(nowTime: number) {
    if (this.activeTime <= 0) return;
    const time = this.activeTime - nowTime;
    if (time > 0) {
      this.timeLab.string = DateUtil.getTimeStr(this.timeMode, time);
    } else {
      this.updateState();
    }
  }

  updateState() {
    switch (this.type) {
      case ActiveTimeType.COUNT_DOWN:
        this.activeTime = 0;
        break;
      case ActiveTimeType.LOOP_POINT:
        {
          this.activeTime = DateUtil.getNextTimePointByTime(GameManager.TimeControl.nowTime, this.loopTimePoint);
        }
        break;
      case ActiveTimeType.LOOP_TIME:
        {
          const now = GameManager.TimeControl.nowTime;
          const time = (now - this.refTimePoint) % this.loopTimePoint;
          this.activeTime = now + (this.loopTimePoint - time);
        }
        break;
    }
  }
}
